package com.example.system.service.impl;

import com.example.springsecurity.custom.CustomUser;
import com.example.system.SysUser;
import com.example.system.service.SysUserService;
import com.example.system.service.UserDetailsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysMenuServiceImpl sysMenuService;

    /**
     * 根据用户名获取用户对象（获取不到直接抛异常）
     * @param username
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = sysUserService.getByUsername(username);
        if(null == sysUser){
            throw new UsernameNotFoundException("用户名不存在！");
        }
        if(sysUser.getStatus().intValue() == 0){
            throw new RuntimeException("账号已停用");
        }

        List<String> userPermsList = sysMenuService.findUserPermsList(sysUser.getId());
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        for (String perm : userPermsList) {
            authorities.add(new SimpleGrantedAuthority(perm.trim()));
        }

//        return new CustomUser(sysUser, Collections.emptyList());
        return new CustomUser(sysUser, authorities);
//        return null;

    }
}
